package com.cxlin.cwanandroid.ui.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.cxlin.base.model.api.Result
import com.cxlin.base.BaseViewModel
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import com.cxlin.cwanandroid.model.bean.Navigation
import com.cxlin.cwanandroid.model.repository.NavigationRepository
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/5/6 10:21
 */
class NavigationViewModel(private val navigationRepository: NavigationRepository) :
    BaseViewModel() {


    sealed class NavigationUiState : UiState {
        object Init : NavigationUiState()
        data class FetchNavigationsSuccess(val navigations: List<Navigation>):NavigationUiState()
    }

    sealed class NavigationEvent : UiEvent {
        class ToastEvent(val message: String, val short: Boolean = false) : NavigationEvent()
    }

    sealed class NavigationUiIntent : UiIntent {
        class GetNavigationList() : NavigationUiIntent()
    }

    override fun handleIntent(intent: UiIntent) {
        when (intent) {
            is NavigationUiIntent.GetNavigationList -> {
                viewModelScope.launch {
                    kotlin.runCatching {
                        val result = navigationRepository.getNavigation()
                        if (result is Result.Success) {
                            mUiStateFlow.update {
                                NavigationUiState.FetchNavigationsSuccess(result.data)
                            }
                        } else if (result is Result.Error) {
                            mEffectFlow.emit(
                                NavigationEvent.ToastEvent(
                                    result.exception.message ?: "网络异常",
                                    true
                                ),
                            )
                        }
                    }
                }
            }
        }
    }

    override fun createInitState(): UiState {
        return NavigationUiState.Init
    }


}